package com.plc.httputils;


import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.log.level.Level;
import com.plc.wmsentity.WmsPlcDataEntity;

import java.util.Date;


public class SendMESHttpRequestUtils {
    static Log log = LogFactory.get();


    /**
     * 向指定URL发送POST请求，发送的数据为WmsPlcDataEntity对象。
     *
     * @param dataEntity WmsPlcDataEntity对象，包含要发送的数据。
     * @param url 发送POST请求的URL。
     * @param token 访问该URL所需的令牌。
     */
    public static void sendPost(WmsPlcDataEntity dataEntity, String url, String token){
        Date date = DateUtil.date();
        String parse = DateUtil.format(date, "yyyy-MM-dd HH:mm:ss.SSS");
        dataEntity.setUploadTime(parse);
        log.log(Level.INFO,"本次调用HTTP,调用[start]数据为{}",JSONUtil.toJsonStr(dataEntity));
        HttpResponse authenticationToken = HttpRequest.post(url)
                .header("AuthenticationToken", token)
                .header("Content-Type", "application/json")
                .header("Accept", "application/json")
                .body(JSONUtil.toJsonStr(dataEntity)).execute(true);

        if(authenticationToken.getStatus()== HttpStatus.HTTP_OK){
            String body = authenticationToken.body();
            if(body!=null) {
                JSONObject entries = JSONUtil.parseObj(body);
                log.log(Level.INFO, "本次调用HTTP wms{},调用结果{}", DateUtil.now(), entries.toString());
                //0-失败，失败需返回错误信息
                //1-成功
                Integer code = entries.get("code", Integer.class);
                if (code.intValue() == 1) {
                    log.log(Level.INFO, "本次调用HTTP wms{},调用结果[success]{}", DateUtil.now(), "成功");
                } else {
                    String message = entries.get("message", String.class);
                    log.log(Level.INFO, "本次调用HTTP WSM{},调用结果[error],原因{}", DateUtil.now(), message);
                }
            }
        }
    }

}
